<template>
  <div>
    <el-dialog @close="handleClose(false)"
               @open="handleOpen"
               close-on-press-escape
               v-dialogDrag
               title="仪表"
               :close-on-click-modal="false"
               :lock-scroll="false"
               :visible="showDialog">
      <el-form :model="form"
               :rules="rules"
               ref="form"
               size="mini"
               label-width="auto"
               class="tabHight_auto">
        <el-row :gutter="20">
          <el-col :span="24"
                  :offset="0">
            <el-form-item label="设备:"
                          prop="deviceToken">
              <el-select v-model="form.deviceToken"
                         :disabled="form.id"
                         placeholder="请选择"
                         class="w100">
                <el-option v-for="item in deviceList"
                           :key="item.token"
                           :label="item.name"
                           :value="item.token">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24"
                  :offset="0">
            <el-form-item label="到期时间:"
                          prop="toDate">
              <el-date-picker :picker-options="forbiddenTime"
                              :append-to-body="false"
                              class="w100"
                              value-format="yyyy-MM-dd"
                              v-model="form.toDate"
                              type="date"
                              placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <div v-for="(item, index) in form.meterList"
               :key="index">
            <el-col :span="form.id ? 12 : 11"
                    :offset="0">
              <el-form-item label="仪表编号:"
                            :prop="'meterList.' + index + '.meterId'"
                            :rules="[
                  {
                    required: true,
                    message: '请输入仪表编号',
                    trigger: 'blur'
                  }
                ]">
                <el-input v-model="item.meterId"
                          placeholder="仪表编号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="form.id ? 12 : 11"
                    :offset="0">
              <el-form-item label="仪表名称:"
                            :prop="'meterList.' + index + '.meterName'"
                            :rules="[
                  {
                    required: true,
                    message: '请输入仪表名称',
                    trigger: 'blur'
                  }
                ]">
                <el-input v-model="item.meterName"
                          placeholder="仪表名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2"
                    :offset="0"
                    v-if="!form.id">
              <span v-if="index == 0"
                    @click="handleAddMeter"
                    class="el-icon-circle-plus"
                    style="margin-top: 6px;font-size: 18px;">
              </span>
              <span v-else
                    @click="handleDelMeter"
                    class="el-icon-remove"
                    style="margin-top: 6px;font-size: 18px;">
              </span>
            </el-col>
          </div>
        </el-row>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button size="mini"
                   @click="handleClose(false)">取 消</el-button>

        <el-button :loading="btnLoading"
                   size="mini"
                   type="primary"
                   @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addMeterManage, updateMeterManage } from "@/api/meterManage";
import { generateId } from "@/utils";
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    deviceList: {
      type: Array,
      default: () => []
    }
  },
  components: {},

  data() {
    return {
      forbiddenTime: {
        //禁用当前日期之前的日期
        disabledDate(time) {
          //  8.64e7 是否包含当前
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      btnLoading: false,
      form: {
        toDate: "",
        deviceToken: "",
        meterList: [
          {
            meterName: "",
            meterId: "",
            id: generateId()
          }
        ]
      },
      rules: {
        deviceToken: [
          { required: true, message: "请选择设备", trigger: "blur" }
        ],
        toDate: [{ required: true, message: "请选择时间", trigger: "change" }]
      }
    };
  },
  mounted() { },
  computed: {},

  methods: {
    handleDelMeter(index) {
      this.form.meterList.splice(index, 1);
    },
    handleAddMeter() {
      this.form.meterList.push({
        meterName: "",
        meterId: "",
        id: generateId()
      });
    },
    //弹窗打开执行操作
    handleOpen() {
      this.form.meterList = [
        {
          meterName: "",
          meterId: "",
          id: generateId()
        }
      ];
    },
    // 弹窗关闭执行操作
    handleClose(isRefresh) {
      this.form = {
        toDate: "",
        deviceToken: "",
        meterList: [
          {
            meterName: "",
            meterId: "",
            id: generateId()
          }
        ]
      };
      this.$refs.form.resetFields();

      this.$emit("update:showDialog", false);
      this.$emit("closeDialog", isRefresh);
      console.log(" this.form :>> ", this.form);
    },
    // 监听图片数组加载完成
    onAddAll(device) {
      let promiseAll = [];
      this.form.meterList.forEach((item, index) => {
        promiseAll[index] = new Promise((resolve, reject) => {
          addMeterManage({
            deviceDes: device.comments,
            deviceName: device.name,
            deviceToken: this.form.deviceToken,
            isToDate: "否",
            token: item.meterId,
            meterId: item.meterId,
            meterName: item.meterName,
            toDate: this.form.toDate
          }).then(res => {
            resolve(1);
          });
        });
      });
      return Promise.all(promiseAll);
    },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const device = this.deviceList.find(
            f => f.token == this.form.deviceToken
          );
          try {
            console.log('id', this.form.id)
            this.btnLoading = true;
            if (!this.form.id) {
              await this.onAddAll(device);
            } else {
              await updateMeterManage(this.form.token, {
                deviceDes: device.comments,
                deviceName: device.name,
                deviceToken: this.form.deviceToken,
                isToDate: this.form.isToDate,
                token: this.form.meterList[0].meterId,
                meterId: this.form.meterList[0].meterId,
                meterName: this.form.meterList[0].meterName,
                toDate: this.form.toDate
              });
            }

            this.btnLoading = false;
            this.handleClose(true);
          } catch (error) {
            this.btnLoading = false;
          }
        } else {
          this.$msg("请完善必要信息");
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped></style>
